package com.xb.cloud.common.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

public class SecurityDigestUtils {

	public static String MD5(String data) {
		return DigestUtils.md5Hex(data);
	}

	public static String SHA1(String data) {
		return DigestUtils.sha1Hex(data);
	}

	private static String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
	private static String KEY_ALGORITHM = "AES";

	public static String AESDecrypt(String data, String key) throws Exception {
		SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("ASCII"), KEY_ALGORITHM);
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		cipher.init(2, keySpec);
		byte[] encrypted1 = Hex.decodeHex(data.toCharArray());
		byte[] original = cipher.doFinal(encrypted1);
		return new String(original, "UTF-8");
	}

	public static String AESEncrypt(String data, String key) throws Exception {
		SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("ASCII"), KEY_ALGORITHM);
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, keySpec);
		byte[] encrypted = cipher.doFinal(data.getBytes("UTF-8"));
		return Hex.encodeHexString(encrypted);
	}

}
